﻿using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;

//---------------------------------------------------------------------------- 
//程序功能	公共函数
//程序名称	/App_Code/Common_Func.cs
//---------------------------------------------------------------------------- 
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Configuration;

namespace XunPan.Web
{
    //FIXME:正規化必要ある？？？？
	public class SecurityUtility
	{
		// Check_ID() 检查账号密码，返回权限
		// 传入参数   Role_Id	角色账号
		// 返回数值	  管理员编号；管理员姓名；权限字符串
		public static string Check_ID(string[] RoleNames)
		{
			string SqlString = "";
			//string mg_id = "";
			string mCheck = "";
			StringBuilder mg_power = new StringBuilder();
			// 取得用户数据 
			using (SqlConnection Sql_Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["XunPanConnectionString"].ToString()) )
            {

				using (SqlCommand Sql_Command = new SqlCommand()) {
					Sql_Conn.Open();
					for (int i = 0; i <= RoleNames.Length - 1; i++) {
						SqlString = "Select Top 1 RoleName, mg_id From aspnet_Roles Where RoleName = @RoleName";
						SqlDataReader Sql_Reader = null;
						Sql_Command.Connection = Sql_Conn;
						Sql_Command.CommandText = SqlString;
						Sql_Command.Parameters.AddWithValue("@RoleName", RoleNames[i]);
						Sql_Reader = Sql_Command.ExecuteReader();
						if (Sql_Reader.Read()) {
							//创建 Session
							string role_mg_id = Sql_Reader["mg_id"].ToString().Trim();
							Sql_Command.Dispose();
							Sql_Reader.Close();
							Sql_Reader.Dispose();

							// 取得运行权限，置入 mg_power
							// 清除 SqlString 字符串
							SqlString.Remove(0, SqlString.Length);

							if (RoleNames[i] == "Administrators") {
								// 若为系统管理员，拥有全部的功能运行权限
								SqlString = "Select fi_no2 From Func_Item2 Where is_visible <> 0";
								//终止循环
								i = RoleNames.Length;
							} else {
								// 一般用户，由人员系统权限 Func_Power 数据表取得可运行的权限，以及系统管理用的功能
								SqlString = "Select fi_no2 From Func_Power Where Role_mg_id = @Role_mg_id And is_enable = 1";
								SqlString = SqlString + " Union ";
								SqlString = SqlString + "Select fi_no2 From Func_Item2 Where is_visible = 2";
							}

							// 取得权限，并填入 mg_power
							Sql_Command.Connection = Sql_Conn;
							Sql_Command.CommandText = SqlString;
							Sql_Command.Parameters.AddWithValue("@Role_mg_id", role_mg_id);
							Sql_Reader = Sql_Command.ExecuteReader();
							while (Sql_Reader.Read()) {
								if (!mg_power.ToString().Contains(Sql_Reader["fi_no2"].ToString())) {
									//避免重复
									mg_power.Append(Sql_Reader["fi_no2"].ToString() + ";");
								}
							}
							Sql_Command.Parameters.Clear();
							Sql_Command.Dispose();
							Sql_Reader.Close();
						}
						Sql_Command.Dispose();
						Sql_Reader.Close();
						Sql_Reader.Dispose();

					}
				}
			}
			mCheck = mg_power.ToString();
			return mCheck;
		}

        		// Check_ID() 检查账号密码，返回权限
		// 传入参数   Role_Id	角色账号
		// 返回数值	  管理员编号；管理员姓名；权限字符串
        public static bool GetRoleNmLastActTime(string userNm,out string roleNmm,out DateTime lastActiveTime)
        {

            roleNmm = "";
            lastActiveTime = DateTime.Now;

            StringBuilder sb = new StringBuilder();
            sb.Append("  SELECT");
            sb.Append("  U.LastActivityDate AS LastActivityDate, ");
            sb.Append("  U.UserName AS UserName, ");
            sb.Append("  R.Description AS RoleName");
            sb.Append("  FROM");
            sb.Append("  aspnet_UsersInRoles AS UR INNER JOIN");
            sb.Append("  aspnet_Roles AS R ON UR.RoleId = R.RoleId INNER JOIN");
            sb.Append("  aspnet_Users AS U ON UR.UserId = U.UserId");
            sb.Append("  WHERE ");
            sb.Append("  (U.UserName = @userNm);");
            using (SqlConnection Sql_Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["XunPanConnectionString"].ToString()))
            {

                using (SqlCommand Sql_Command = new SqlCommand())
                {
                    Sql_Conn.Open();

                    SqlDataReader Sql_Reader = null;
                    Sql_Command.Connection = Sql_Conn;
                    Sql_Command.CommandText = sb.ToString();
                    Sql_Command.Parameters.AddWithValue("@userNm", userNm);
                    Sql_Reader = Sql_Command.ExecuteReader();
                    if (Sql_Reader.Read())
                    {
                        //创建 Session
                        roleNmm = Sql_Reader["RoleName"].ToString().Trim();
                        lastActiveTime = Convert.ToDateTime( Sql_Reader["LastActivityDate"].ToString());

                        Sql_Command.Dispose();
                        Sql_Reader.Close();
                    }
                }
                Sql_Conn.Dispose();
                Sql_Conn.Close();
                Sql_Conn.Dispose();
            }
            return true;
        }


		// Check_Power() 检查权限并保存
		// 输入参数	mg_sid		管理员代码
		//			mg_name		管理员姓名
		//			mg_power	权限字符串
		//			f_power		现行程权限代码
		// 返回数值	 0	正确
		//			-1	不明原因错误
		//			-2	登录数据错误 (不正常的方式进入)
		//			-3	无指定功能的使用权限	

		//public int Check_Power(string role_mg_id, string user_name, string mg_power, string f_power)
		public static int Check_Power(string user_name, string mg_power, string f_power)
		{
			//String_Func sfc = new String_Func();
			int mfg = -1;
			//string SqlString = "";
			//SqlConnection Sql_Conn;
			//SqlCommand Sql_Command;

			//if (sfc.IsInteger(role_mg_id))
			//{
			if (string.IsNullOrEmpty(user_name)) {
				mfg = -2;
			} else {
				if (mg_power.Contains(f_power)) {
					mfg = 0;
				} else {
					mfg = -3;
				}
			}
			//}
			//else
			//    mfg = -2;

			//if (mfg == 0 && bl_save)
			//
			//    SqlString = "Insert Into Mg_Log (mg_sid, fi_no2, lg_time, lg_ip) Values";
			//    SqlString = SqlString + " (@mg_sid, @fi_no2, getdate(), @lg_ip)";
			//    Sql_Conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["AppSysConnectionString"].ConnectionString);
			//    Sql_Conn.Open();
			//    Sql_Command = new SqlCommand(SqlString, Sql_Conn);
			//    Sql_Command.Parameters.AddWithValue("@mg_sid", mg_sid);
			//    Sql_Command.Parameters.AddWithValue("@fi_no2", f_power);
			//    Sql_Command.Parameters.AddWithValue("@lg_ip", lg_ip);

			//    Sql_Command.ExecuteNonQuery();

			//    Sql_Command.Dispose();
			//    Sql_Conn.Close();
			//}

			return mfg;
		}

		// CleanSQL() 清除字符串中有 SQL 代码注入攻击的字符串 ‘'’‘ ’‘;’‘--’ ‘|’‘\t’‘\n’
		public static string CleanSQL(string mString)
		{
			if (mString == null) {
				mString = "";
			} else {
				mString = mString.Replace("'", "''");
				mString = mString.Replace(" ", "");
				mString = mString.Replace(";", "");
				mString = mString.Replace("--", "");
				mString = mString.Replace("|", "");
				mString = mString.Replace(Constants.vbTab, "");
				mString = mString.Replace(Constants.vbLf, "");
			}
			return mString;
		}

		// CheckSQL() 检查字符串中有 SQL 代码注入攻击的字符串 ‘'’‘;’‘--’‘|’‘\t’‘\n’
		public static bool CheckSQL(string mString)
		{
			bool mfg = false;

			if (mString == null) {
				mfg = true;
			} else {
				mfg = (mString.Contains("'") || mString.Contains(" ") || mString.Contains(";") || mString.Contains("--") || mString.Contains("|") || mString.Contains(Constants.vbTab) || mString.Contains(Constants.vbLf));
			}

			return mfg;
		}
	}

}
